// 修改导入语句
import { createRouter, createWebHashHistory } from 'vue-router';
import { useUserStore } from '../stores/user';

import ArticleListView from '../views/ArticleListView.vue';
import PublishArticleView from '../views/PublishArticleView.vue';
import LoginView from '../views/LoginView.vue';
import RegisterView from '../views/RegisterView.vue';
import ArticleDetailView from '../views/ArticleDetailView.vue';
import ProductListView from '../views/ProductListView.vue';
import AddProductView from '../views/AddProductView.vue';
import MovieListView from '../views/MovieListView.vue';
import MovieDetailView from '../views/MovieDetailView.vue';
import AddMovieView from '../views/AddMovieView.vue'; 
import HomeView from '@/views/HomeView.vue';

const router = createRouter({
  // 将createWebHistory改为createWebHashHistory
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/home',
      name: 'home',
      component: HomeView
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: { title: '登录', guestOnly: true }
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView
    },
    {
      path: '/articles',
      name: 'articles',
      component: ArticleListView
    },
    {
      path: '/publish',
      name: 'publish',
      component: PublishArticleView,
      meta: { requiresAuth: true, title: '发布文章' }
    },
    {
      path: '/articles/:id',
      name: 'article-detail',
      component: ArticleDetailView,
      props: true
    },
    {
      path: '/products',
      name: 'products',
      component: ProductListView
    },
    {
      path: '/add-product',
      name: 'add-product',
      component: AddProductView
    },
    {
      path: '/product-detail/:id',
      name: 'ProductDetail',
      component: () => import('../views/ProductDetailView.vue')
    },
    {
      path: '/movies',
      name: 'movies',
      component: MovieListView,
    },
    {
      path: '/movie/:id',
      name: 'movie-detail',
      component: MovieDetailView,
      props: true
    },
    {
      path: '/add-movie', 
      name: 'add-movie',
      component: AddMovieView
    }
  ]
});

router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  const isAuthenticated = userStore.isLoggedIn;

  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login');
  } else if ((to.name === 'login' || to.name === 'register') && isAuthenticated) {
    next('/articles');
  } else {
    next();
  }
});

export default router;